<?php

namespace app\common\validate\tyyh;

class UserCart extends Base
{
	/**
     * 验证规则
     */
    protected $rule = [
        'lock'                => 'require',
        'id'                  => 'require',
        'ids'                 => 'require|isUsers:tyyh\\UserCart',
        'uid'                 => 'require',
        'sid'                 => 'require|integer|isShow:tysj\\Store',
        'pid'                 => 'require|integer|isOwner:tysj\\Product',
        'psid'                => 'require|integer|isProduct',
        'num'                 => 'require|integer|gt:0|minBuy'
    ];


    /**
     * 提示消息
     */
    protected $message = [
        'lock.require'                  => '验证规则场景不存在',
        'id.require'                    => '购物车ID不能为空',
        'id.isUser'                     => '购物车ID不属于您或已删除',
        'uid.require'                   => '用户ID不能为空',
        'sid.require'                   => '店铺ID不能为空',
        'sid.integer'                   => '店铺ID必须是一个数字',
        'sid.isShow'                    => '商家已经闭店',
        'pid.require'                   => '产品ID不能为空',
        'pid.integer'                   => '产品ID必须是一个数字',
        'pid.isOwner'                   => '产品不属于店铺',
        'psid.require'                  => '规格ID不能为空',
        'psid.integer'                  => '规格ID必须是一个数字',
        'psid.isProduct'                => '规格已被产品移除',
        'num.require'                   => '购买数量不能为空',
        'num.integer'                   => '购买数量必须是一个整数',
        'num.gt'                        => '购买数量必须大于0',
        'num.minBuy'                    => '购买数不足'
    ];
    /**
     * 验证场景
     */
    protected $scene = [
        'save'        => [
            'id' => 'isUser:tyyh\\UserCart',
            'uid',
            'sid',
            'pid',
            'psid',
            'num'
        ],
        'private'     => ['uid'],
        'info'        => ['id' => 'isUser:tyyh\\UserCart'],
        'set_num'     => ['id' => 'require|isUser:tyyh\\UserCart', 'num'],
        'del'         => ['id' => 'require|isUser:tyyh\\UserCart'],
        'dels'        => ['ids']
    ];

    // 验证最小购买数
    protected function minBuy($value, $rule, $data = []) {
        $psid = '';
        if(isset($data['psid'])) {
            $psid = $data['psid'];
        } else {
            $cart = loadOnly('Model')->find('tyyh\\UserCart', $data['id']);
            $psid = $cart['psid'];
        }
        $row = loadOnly('Model')->find('tysj\\ProductSpecs', $psid);
        return $row && $row['min_purchase_quantity'] <= $value;
    }

    /*
     *  验证规格是否属于产品
     */
    protected function isProduct($value, $rule, $data = []) {
        $count = loadModel('tysj\\ProductSpecsNexus')->where(['pid' => $data['pid'], 'psid' => $value])->count();
        return $count > 0;
    }
}
